﻿using System;
using System.Configuration;
using System.Data.Linq;
using System.Linq;
using BusinessLogic.Model;
using BusinessLogic.StateManagers;
using BusinessLogic;

namespace Admin
{
    public partial class EditNewsItem : System.Web.UI.Page
    {

        #region Properties

        private NewsItem NewsItem { get; set; }
        private BlogNETDataContext dc;

        #endregion

        #region PageEvents

        protected void Page_PreInit(object sender, EventArgs e)
        {
            int newsItemID;

            if (!Int32.TryParse(Request.QueryString[QueryStringConstants.NewsItemID], out newsItemID))
            {
                Session[Constants.Session.ErrorMessage] = Constants.Error.InvalidQueryString;
                Server.Transfer("~/Error.aspx");
            }

            dc = new BlogNETDataContext(ConfigurationManager.ConnectionStrings["BlogNETDB"].ConnectionString);
            DataLoadOptions dlo = new DataLoadOptions();
            dlo.LoadWith<NewsItem>(ni => ni.Tags);
            dc.LoadOptions = dlo;

            var item = from ni in dc.NewsItems
                       where ni.NewsItemID == newsItemID
                       select ni;

            NewsItem = item.Single<NewsItem>();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            nieEditor.NewsItem = this.NewsItem;
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            if (dc != null)
            {
                dc.Dispose();
            }
        }

        #endregion

        #region ControlEvents

        protected void nieEditor_Save(object sender, EventArgs e)
        {
            //clear tags cache because the tags may have changed making the cache invalid
            Cache.Remove(Constants.Cache.Tags);
            //clear latest comments cache because the title may have changed
            CacheManager.RemoveLatestComments();

            dc.SubmitChanges();

            //dc.Dispose();

            Response.Redirect("~/ViewNewsItem.aspx?" + QueryStringConstants.NewsItemID + "=" + NewsItem.NewsItemID);
        }

        #endregion

    }
}